<script setup>
import { onLoad } from "@dcloudio/uni-app";
import { httpRequest } from "../../utils/http";
import { computed, ref, reactive} from "vue";
const textList = ref([])
textList.value = uni.getStorageSync('textList')
console.log(textList.value);

// const videoArr = ref([
//     ref([]),ref([]),ref([]),ref([]),ref([]),ref([]),ref([]),ref([]),ref([]),ref([]),ref([]),ref([]),ref([]),ref([]),ref([]),ref([]),ref([]),ref([]),ref([]),ref([]),ref([]),ref([]),ref([]),ref([]),ref([]),ref([]),ref([]),ref([]),ref([]),ref([]),ref([]),ref([]),ref([]),ref([]),ref([])
//     ,ref([]),ref([]),ref([]),ref([]),ref([]),ref([]),ref([]),ref([]),ref([]),ref([]),ref([]),ref([]),ref([]),ref([]),ref([]),ref([]),ref([]),ref([]),ref([]),ref([]),ref([]),ref([]),ref([]),ref([]),ref([]),ref([]),ref([]),ref([]),ref([]),ref([]),ref([]),ref([]),ref([]),ref([]),ref([])
// ])
const videoArr = reactive([
  [],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[]
])

const type = ref(0)
const lei = ref('')
onLoad((e)=>{
  if(e.lei){
    lei.value = e.lei
  }
  if(e.type){
    type.value=e.type
    uni.setStorageSync('up',type.value)
  }
  type.value = uni.getStorageSync('up')
  getVideos()
})
const time = ref(0)
const isCross = ref(0)
const getSelectVideo = (num) => {
  uni.vibrateShort()
  console.log(num);
  //选择视频
  uni.chooseVideo({
    maxDuration:60,
    // compressed:false,
    success: async (res) => {
      console.log(res);
      if(lei.value=='pub'&&(res.height>res.width))return uni.showToast({title:`产品宣传请统一上传横屏的视频`,icon:'none'})
      if(res.duration<(textList.value[num].length / 3))return uni.showToast({title:`请上传至少${Math.floor(textList.value[num].length / 3)}秒的视频`,icon:'none'}) 
      if(videoArr[num].length+1>10)return uni.showToast({title:'上传视频不能超过十个',icon:'none'})
      if (res.duration < 7)return uni.showToast({ title: `请上传至少7秒的视频`, icon: "none" });
      console.log(res.tempFilePath);
      
      if(!isCross.value){
        isCross.value = res.height>=res.width?1:2
      }
      console.log(isCross.value);
      if((isCross.value == 1&&res.height<res.width)||(isCross.value == 2&&res.height>=res.width)){
        uni.showToast({
          title:`请统一上传${isCross.value==1?'竖屏':'横屏'}的视频`,
          icon:'none'
        })
        return
      }
      uni.showLoading({
        title: "上传中",
        mask: true,
      });
      time.value = time.value + res.duration
      uni.setStorageSync('videoTime',time.value)
      // uni.getVideoInfo({
      //   src:res.tempFilePath,
      //   success:(res)=>{
          console.log(res);
          console.log(uni.getStorageSync('num')[num]);
          uni.uploadFile({
        // url: 'https://www.diandianyouke.cn:8081/api/editVideosOne1',
        url: "https://www.diandianyouke.cn:8081/api/editVideosOne2",
        fileType: "video",
        filePath: res.tempFilePath,
        name: "video",
        header: {
          "Content-Type": "multipart/form-data",
          token: uni.getStorageSync("token"),
        },
        formData: { 
          // num: uni.getStorageSync('num')?uni.getStorageSync('num')[num]:num+1,
          num: num+1,
          businessId:uni.getStorageSync('business').businessId,
          type:2, 
          fblW:-1,fblH:-1
      },
        success: async ({ data, statusCode }) => {
          console.log(JSON.parse(data));
          if (JSON.parse(data).code == "0") {
            uni.hideLoading();
            uni.showToast({
              title: "上传成功",
              icon: "success",
              mask:false
            });
            videoArr[num].push(JSON.parse(data).data);
            console.log(videoArr);
            let v = videoArr.filter(e=>e.length)
            uni.setStorageSync('videoArr', videoArr)
          } else {
            uni.showToast({title:'上传失败',icon:'error'})
          }
        },
        fail: (error) => {
          console.log(error);
          uni.showToast({title:'上传失败,请重试',icon:'error'})
        },
      });
      const res1 = await httpRequest("/api/findTaskStart", "POST", {
              businessId: uni.getStorageSync("business").businessId,
            });
            console.log(res1);
            if (!res1.data) {
              
              const res2 = await uni.request({
                url: "https://www.diandianyouke.cn:8081/api/addTask",
                method: "POST",
                header: {
                  "Content-Type": "application/json",
                },
                data: {
                  businessId: uni.getStorageSync("business").businessId,
                  shopId: uni.getStorageSync("shop")[uni.getStorageSync("index")].shopId,
                  type: lei.value,
                },
              });
              uni.setStorageSync("taskId", res2.data.data.id);
              const n = []
              for (let i = 0; i < textList.value.length; i++) {
                n.push(i+1)
              }
              uni.setStorageSync('num',n)
              httpRequest('/api/generateTitle','POST',{
                shopId:uni.getStorageSync("shop")[uni.getStorageSync("index")].shopId,
                taskId:res2.data.data.id,
                // product:uni.getStorageSync('templateId')?uni.getStorageSync('templateId').product:''
              })
              uni.hideLoading()
              if(type=='same'){
                httpRequest('/api/downloadPopVideoVoice','POST',{
                  id:uni.getStorageSync('same').popVideoId,
                  businessId:uni.getStorageSync('business').businessId
                },20000)
              }
            }
    },
    fail: (error) => {
      console.error("读取文件失败", error);
    },
  });
};

const delVideo = async (url, i) => {
  await httpRequest("/api/delVideosOne2", "POST", {
    videoPath: url,
  });
  videoArr[i] = videoArr[i].filter((e) => e != url);
  console.log(videoArr);
  if (videoArr.every((e) => e.length == 0)) {
    await httpRequest("/api/delTask", "POST", {
      taskId: uni.getStorageSync("taskId"),
    });
    isCross.value = 0
    videoArr.forEach(e=>{
      e = []
    })
    uni.removeStorageSync("videoArr");
  }
  console.log((videoArr.filter(e=>e.length)).length);
   if(((videoArr.filter(e=>e.length)).length==5)||((videoArr.filter(e=>e.length)).length==3)){
      isReady.value = true
    }else{
      isReady.value = false
    }
};

//获取临时文件
const getVideos = async() => {
  console.log(type.value);
  const res = await httpRequest('/api/getVideosOne2','POST',{
    businessId: uni.getStorageSync("business").businessId,
    // type:type.value?'up':''
  })
  console.log(res);
  if(!res.data.length){
    videoArr.forEach(e=>{
      e = []
    })
  }else{
    res.data.forEach(e=>{
      videoArr[e.index-1] = e.lists.map(e=>e.url)
    })
  }
}

console.log(videoArr);

const lastPage = () => {
    uni.redirectTo({ url: `/pageA/index/section?lei=${lei.value}` })
}

const nextPage = () => {
    if((videoArr.filter(e=>e.length)).length<textList.value.length)return uni.showToast({title:'请先上传视频',icon:'none'})
    uni.navigateTo({ url: `/pageA/index/IPMaster2` })
}
</script>

<template>
  <view>
    <view style="background-color: rgba(246, 248, 251, 1); overflow: hidden;">
    <view style="padding-bottom: 200rpx">
      <view class="items" v-for="(e, i) in textList" :key="i">
        <view class="title">
          <text>{{ e }}<text style="color: rgb(255,55,71);">*</text></text>
        </view>
        <view>
          <view class="videos">
            <view class="addVideo" @click="getSelectVideo(i)">
              <image
                style="width: 80rpx; height: 75rpx"
                src="https://www.diandianyouke.site:801/fileDataBase/static/stag/static/img/icon_shipinsc.png"
                mode="scaleToFill"
              />
              <text style="font-size: 24rpx; color: rgba(142, 84, 244, 1)">添加视频</text>
            </view>
            <scroll-view
              scroll-x="true"
              style="white-space: nowrap; float: right; width: 520rpx; height: 200rpx;"
            >
              <view
                style="
                  padding-top: 18rpx;
                  display: inline-block;
                  position: relative;
                  width: 184rpx;
                  height: 178rpx;
                  box-sizing: border-box;
                "
                v-for="(item, index) in videoArr[i]"
                :key="index"
              >
                <view v-if="item">
                    <video
                  :src="item"
                  style="
                    width: 160rpx;
                    height: 160rpx;
                    display: inline-block;
                    border-radius: 16rpx;
                  "
                ></video>
                <image
                  @click="delVideo(item, i)"
                  style="
                    width: 48rpx;
                    height: 48rpx;
                    position: absolute;
                    right: 0;
                    top: 0;
                  "
                  src="https://www.diandianyouke.site:801/fileDataBase/static/stag/static/img/xxxx.png"
                  mode=""
                />
                </view>
              </view>
            </scroll-view>
          </view>
        </view>
      </view>
    </view>
  </view>
  <view class="btns">
        <button hover-class="hover" class="last" @click="lastPage">上一步</button>
        <button hover-class="hover" class="next" @click="nextPage">下一步</button>
    </view>
  </view>
</template>

<style lang="scss">
.items {
  padding: 36rpx 30rpx;
  margin-top: 24rpx;
  background-color: #fff;
  .title {
    display: flex;
    justify-content: space-between;
    align-items: center;
    line-height: 96rpx;
    font-size: 32rpx;
    margin-bottom: 20rpx;
    font-weight: 700;
    color: rgb(48, 49, 51);
    line-height: 46rpx;
  }
  .videos {
    display: flex;
    margin-top: 20rpx;
    .addVideo {
      width: 160rpx;
      height: 160rpx;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      border: 1px dashed rgba(142, 84, 244, 1);
      margin-right: 10rpx;
      border-radius: 16rpx;
      transform: translateY(18rpx);
      margin-bottom: 36rpx;
    }
  }
}
.btns{
            position: fixed;
            bottom: 0;
            left: 0;
            width: 100%;
            height: 166rpx;
            padding-top: 10rpx;
            box-sizing: border-box;
            display: flex;
            justify-content: center;
            background-color: #fff;
            .last{
                width: 240rpx;
                height: 88rpx;
                text-align: center;
                line-height: 88rpx;
                background-color: #fff;
                border-radius: 8rpx;
                color: rgb(142,84,244);
                border: 1px solid rgb(142,84,244);
                font-size: 32rpx;
                margin: 0;
            }
            .next{
                width: 420rpx;
                height: 88rpx;
                background-color: rgb(142,84,244);
                border-radius: 8rpx;
                color: #fff;
                font-size: 32rpx;
                text-align: center;
                line-height: 88rpx;
                margin: 0;
                margin-left: 30rpx;
            }
        }
        .hover{
          opacity: 0.7;
        }
</style>


